<template>
    <div class="h-start-start h100 w100">
        <div class="tree-content h100 w20 p20">
            <div class="v-start-start">
                <div v-if="$store.state.userInfo.roleCode > 2" class="h-start-center mr20">
                    综评得分：
                    <div class="red">{{ zhpScoreTotal }}</div>
                </div>
                <div v-if="record.xzjbName === '县（市、区）'" class="h-start-center">
                    复核得分：
                    <div class="red">{{ shScoreTotal }}</div>
                </div>
                <div class="h-start-center mr20">
                    自评得分：
                    <div class="red">{{ selfEvaluationScore }}</div>
                </div>
                <div class="red">(未加权)</div>
            </div>
            <a-tree
                v-if="treeData.length > 0"
                :replace-fields="{
                    key: 'templateId',
                }"
                :tree-data="treeData"
                show-icon
                default-expand-all
                @select="treeSelected"
                :selectedKeys="currentTreeNode"
            >
                <a-icon slot="switcherIcon" type="down" />
                <template slot="custom" slot-scope="{ ifRecord }">
                    <svg-icon
                        slot="custom"
                        icon-class="circle"
                        class="f8"
                        :class="ifRecord ? 'green' : 'gray'"
                    ></svg-icon>
                </template>
            </a-tree>
        </div>
        <div class="bg-white w80 selfEvaluation">
            <a-table
                bordered
                v-if="tableData.length > 0"
                rowKey="id"
                :columns="columns"
                :data-source="tableData"
                @change="handleTableChange"
                :key="tableKey"
                :pagination="false"
                :scroll="{ x: 1500, y: true }"
            >
                <!--自评相关-->
                <template slot="zpMissItem" slot-scope="text, record">
                    <a-switch
                        :disabled="true"
                        v-model="record.zpMissItem"
                        @change="tableChange($event, record.id, 'zpMissItem')"
                    />
                </template>
                <template slot="file" slot-scope="text, record">
                    <a-upload
                        :disabled="true"
                        :before-upload="beforeUpload"
                        :action="uploadFileUrl"
                        name="file"
                        :multiple="true"
                        @change="uploadFileChange($event, record.id)"
                        :accept="fileType"
                        :default-file-list="record.file"
                        :headers="{
                            token: fileToken,
                        }"
                        @preview="previewFile"
                    >
                        <a-button v-if="!record.file">
                            <a-icon type="upload" />
                            上传pdf文件
                        </a-button>
                    </a-upload>
                </template>
                <template slot="zpScore" slot-scope="text, record">
                    <a-input-number
                        :disabled="true"
                        :value="text"
                        :min="0"
                        :max="record.score"
                        :step="0.1"
                        :precision="2"
                        @blur="tableChange($event.target.value, record.id, 'zpScore')"
                    />
                </template>
                <template slot="zpRemarks" slot-scope="text, record">
                    <a-textarea
                        :autoSize="true"
                        :disabled="true"
                        :value="text"
                        placeholder="请输入"
                        @change="tableChange($event.target.value, record.id, 'shRemarks')"
                    />
                </template>

                <!--审核相关-->
                <template slot="shMissItem" slot-scope="text, record">
                    <a-switch
                        :disabled="!isEdit || $store.state.userInfo.roleCode > 2"
                        v-model="record.shMissItem"
                        @change="tableChange($event, record.id, 'shMissItem')"
                    />
                </template>
                <template slot="shScore" slot-scope="text, record">
                    <a-input-number
                        :disabled="!isEdit || $store.state.userInfo.roleCode > 2 || record.shMissItem"
                        :value="text"
                        :min="0"
                        :max="record.score"
                        :step="0.1"
                        :precision="2"
                        @change="tableChange($event, record.id, 'shScore')"
                    />
                </template>
                <template slot="shRemarks" slot-scope="text, record">
                    <a-textarea
                        :autoSize="true"
                        :disabled="!isEdit || $store.state.userInfo.roleCode > 2"
                        :value="text"
                        placeholder="请输入审核备注"
                        @change="tableChange($event.target.value, record.id, 'shRemarks')"
                    />
                </template>

                <!--综评相关-->
                <template slot="zhpMissItem" slot-scope="text, record">
                    <a-switch
                        :disabled="!isEdit"
                        v-model="record.zhpMissItem"
                        @change="tableChange($event, record.id, 'zhpMissItem')"
                    />
                </template>
                <template slot="zhpScore" slot-scope="text, record">
                    <a-input-number
                        :disabled="!isEdit || record.zhpMissItem"
                        :value="text"
                        :min="0"
                        :max="record.score"
                        :step="0.1"
                        :precision="2"
                        @change="tableChange($event, record.id, 'zhpScore')"
                    />
                </template>
                <template slot="zhpRemarks" slot-scope="text, record">
                    <a-textarea
                        :autoSize="true"
                        :disabled="!isEdit"
                        :value="text"
                        placeholder="请输入审核备注"
                        @change="tableChange($event.target.value, record.id, 'zhpRemarks')"
                    />
                </template>
            </a-table>
        </div>
    </div>
</template>

<script>
import { getFileToken } from '@/common/api/common'
import url from '@/common/url-config.js'
import { selfEvaluationRecordApi, selfEvaluationApi } from '@/common/api/selfEvaluation'
import { debounce } from 'throttle-debounce'
let me
export default {
    props: {
        record: {
            required: true,
            type: Object,
        },
        isEdit: {
            default: true,
            type: Boolean,
        },
    },
    data() {
        return {
            originTreeData: [],
            fileSrc: '',
            tableKey: +new Date(),
            fileType: '.pdf',
            uploadFileUrl: url.uploadFile,
            fileToken: '',
            columns: [
                {
                    title: '三级项',
                    dataIndex: 'three',
                    width: 100,

                    customRender: (value, row, index) => {
                        const obj = {
                            children: value,
                            attrs: { rowSpan: row.rowSpan },
                        }

                        return obj
                    },
                },
                {
                    title: '评价内容',
                    dataIndex: 'four',
                    width: 200,
                },
                {
                    title: '评价操作指南',
                    dataIndex: 'operationGuide',
                    width: 200,
                },
                {
                    title: '自评缺项',
                    width: 90,
                    dataIndex: 'zpMissItem',
                    scopedSlots: { customRender: 'zpMissItem' },
                },
                {
                    title: '资料上传',
                    dataIndex: 'file',
                    align: 'center',
                    scopedSlots: { customRender: 'file' },
                    width: 170,
                },
                {
                    title: '自评得分',
                    dataIndex: 'zpScore',
                    scopedSlots: { customRender: 'zpScore' },
                    width: 120,
                },
                {
                    title: '自评加/扣分原因',
                    dataIndex: 'zpRemarks',
                    width: 120,
                    scopedSlots: { customRender: 'zpRemarks' },
                },
            ],
            tableLoading: false,
            currentTreeNode: [],
        }
    },
    mounted() {
        me = this
        setTimeout(() => {
            this.originTreeData = this.record?.evaluationList || []

            if (this.$store.state.userInfo.roleCode > 2) {
                if (this.record.xzjbName === '县（市、区）') {
                    let brr = [
                        {
                            title: '复核缺项',
                            dataIndex: 'shMissItem',
                            scopedSlots: { customRender: 'shMissItem' },
                            width: 90,
                        },
                        {
                            title: '复核得分',
                            dataIndex: 'shScore',
                            scopedSlots: { customRender: 'shScore' },
                            width: 120,
                        },
                        {
                            title: '复核加/扣分原因',
                            dataIndex: 'shRemarks',
                            width: 140,
                            scopedSlots: { customRender: 'shRemarks' },
                        },
                    ]
                    this.columns.push(...brr)
                }
                let arr = [
                    {
                        title: '综评缺项',
                        dataIndex: 'zhpMissItem',
                        width: 120,
                        scopedSlots: { customRender: 'zhpMissItem' },
                    },
                    {
                        title: '综评得分',
                        dataIndex: 'zhpScore',
                        width: 120,
                        scopedSlots: { customRender: 'zhpScore' },
                    },
                    {
                        title: '综评加/扣分原因',
                        dataIndex: 'zhpRemarks',
                        width: 140,
                        scopedSlots: { customRender: 'zhpRemarks' },
                    },
                ]
                this.columns.push(...arr)
            } else {
                let arr = [
                    {
                        title: '复核缺项',
                        dataIndex: 'shMissItem',
                        scopedSlots: { customRender: 'shMissItem' },
                        width: 90,
                    },
                    {
                        title: '复核得分',
                        dataIndex: 'shScore',
                        scopedSlots: { customRender: 'shScore' },
                        width: 120,
                    },
                    {
                        title: '复核加/扣分原因',
                        dataIndex: 'shRemarks',
                        width: 140,
                        scopedSlots: { customRender: 'shRemarks' },
                    },
                ]
                this.columns.push(...arr)
            }

            this._columns = [...this.columns]
        }, 100)
    },
    destroyed() {
        me = null
    },
    computed: {
        selfEvaluationScore() {
            let score = 0
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            if (originArr.length > 0) {
                score = originArr.reduce((total, item) => {
                    let zpScore = item.zpScore || 0
                    return total + zpScore
                }, 0)
            }
            return score.toFixed(2)
        },
        shScoreTotal() {
            let score = 0
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            if (originArr.length > 0) {
                score = originArr.reduce((total, item) => {
                    let score = item.shScore ? item.shScore : 0
                    return total + score
                }, 0)
            }
            return score.toFixed(2)
        },
        zhpScoreTotal() {
            let score = 0
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            if (originArr.length > 0) {
                score = originArr.reduce((total, item) => {
                    let score = item.zhpScore ? item.zhpScore : 0
                    return total + score
                }, 0)
            }
            return score.toFixed(2)
        },
        tableData() {
            if (this.treeData.length < 0) {
                return []
            }
            let levelTwoId = this.currentTreeNode[0]
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            originArr = originArr.sort((a, b) => a.sortNum - b.sortNum)
            let threeArr = originArr.filter(item => item.level === 3 && item.parentId === levelTwoId)
            let threeSort = {}
            threeArr.forEach((item, index) => {
                threeSort[item.templateId] = index
            })
            let fourArr = originArr.filter(item => item.level === 4)
            fourArr = fourArr.filter(item => {
                item.fourSort = threeSort[item.parentId]
                let three = null
                for (let i = 0; i < threeArr.length; i++) {
                    if (threeArr[i].templateId === item.parentId) {
                        three = threeArr[i]
                        break
                    }
                }
                if (three) {
                    item.threeName = three.name
                    item.twoId = three.parentId
                    if (item.zpArchiveJson) {
                        item.file = JSON.parse(item.zpArchiveJson)
                    } else {
                        item.file = null
                    }

                    item.zpScore = item.zpScore || 0
                    item.shScore = item.shScore || 0
                    item.zhpScore = item.zhpScore || 0

                    return true
                }
                return false
            })
            fourArr = fourArr.sort((a, b) => a.fourSort - b.fourSort)
            let parentId = null
            let count = 0
            let startRow = null
            for (let i = 0; i < fourArr.length; i++) {
                let four = fourArr[i]
                if (parentId === four.parentId) {
                    four.rowSpan = 0
                    startRow.threeScore += four.score
                    count++
                } else {
                    startRow = four
                    startRow.threeScore = four.score
                    parentId = four.parentId
                    count = 1
                }
                startRow.rowSpan = count
            }
            fourArr.forEach(item => {
                item.four = `${item.name} (${item.score.toFixed(2)}分)`
                if (item.threeScore) {
                    item.three = `${item.threeName} (${item.threeScore.toFixed(2)}分)`
                }
            })
            return fourArr
        },
        treeData() {
            let originArr = JSON.parse(JSON.stringify(this.originTreeData))
            originArr = originArr.sort((a, b) => a.sortNum - b.sortNum)
            let oneArr = originArr.filter(item => item.level === 1)
            let twoArr = originArr.filter(item => item.level === 2)
            let threeArr = originArr.filter(item => item.level === 3)
            let fourArr = originArr.filter(item => item.level === 4)
            fourArr.forEach(fourItem => {
                let zpScore = fourItem.zpScore || 0
                for (let i = 0; i < threeArr.length; i++) {
                    let threeItem = threeArr[i]
                    if (fourItem.parentId === threeItem.templateId) {
                        if (threeItem.zpScore !== null) {
                            threeItem.zpScore += zpScore
                            threeItem.ifRecord = threeItem.ifRecord || fourItem.ifRecord
                            threeItem.score += fourItem.score
                        } else {
                            threeItem.zpScore = zpScore
                            threeItem.ifRecord = fourItem.ifRecord
                            threeItem.score = fourItem.score
                        }
                        break
                    }
                }
            })
            threeArr.forEach(threeItem => {
                let zpScore = threeItem.zpScore || 0
                for (let i = 0; i < twoArr.length; i++) {
                    let twoItem = twoArr[i]
                    if (threeItem.parentId === twoItem.templateId) {
                        if (twoItem.zpScore !== null) {
                            twoItem.zpScore += zpScore
                            twoItem.score += threeItem.score
                            twoItem.ifRecord = twoItem.ifRecord || threeItem.ifRecord
                        } else {
                            twoItem.zpScore = zpScore
                            twoItem.score = threeItem.score
                            twoItem.ifRecord = threeItem.ifRecord
                        }
                        break
                    }
                }
            })
            twoArr.forEach(twoItem => {
                let zpScore = twoItem.zpScore || 0
                twoItem.zpScore = +(Math.round(zpScore * 100) / 100).toFixed(2)
                twoItem.score = +(Math.round(twoItem.score * 100) / 100).toFixed(2)
                twoItem.title = `${twoItem.name}(${zpScore}/${twoItem.score})分`
                twoItem.scopedSlots = {
                    icon: 'custom',
                }
                for (let i = 0; i < oneArr.length; i++) {
                    let oneItem = oneArr[i]
                    if (twoItem.parentId === oneItem.templateId) {
                        if (oneItem.zpScore !== null) {
                            oneItem.zpScore += zpScore
                            oneItem.score += twoItem.score
                            oneItem.ifRecord = oneItem.ifRecord || twoItem.ifRecord
                            oneItem.children.push(twoItem)
                        } else {
                            oneItem.zpScore = zpScore
                            oneItem.score = twoItem.score
                            oneItem.ifRecord = twoItem.ifRecord
                            oneItem.children = [twoItem]
                        }
                        break
                    }
                }
            })
            oneArr.forEach(item => {
                let zpScore = item.zpScore || 0
                item.selectable = false //一级节点禁止选择
                item.zpScore = +(Math.round(zpScore * 100) / 100).toFixed(2)
                item.score = +(Math.round(item.score * 100) / 100).toFixed(2)
                item.title = `${item.name}(${zpScore}/${item.score})分`
                item.scopedSlots = {
                    icon: 'custom',
                }
            })
            if (this.currentTreeNode.length <= 0 && oneArr[0]?.children[0]?.templateId) {
                this.currentTreeNode = [oneArr[0]?.children[0]?.templateId] || []
            }
            return oneArr
        },
    },
    methods: {
        uploadFileChange(info, id) {
            let fileList = [...info.fileList]
            let file = fileList[0] || {}
            if (file.response && file.status === 'done') {
                file.fileId = file.response.data.id
                file.url = file.fileId // 给file赋url字体才能变蓝
                this.tableChange(file.fileId, id, 'zpArchiveId')
                this.tableChange(file.name, id, 'zpArchiveName')
            }
            if (file.status === 'error') {
                if (file.response.errorCode === 401) {
                    this.$notification401(file.response.message)
                }
                file.response = file.response.message || '服务器异常'
            }
        },

        previewFile(file) {
            let { uid: fileId, name: fileName } = file
            let fileType = 'pdf'
            const fileSrc = `/file/api/Preview/v1/${fileId}`
            if (fileType === 'pdf') {
                this.fileSrc = `/pdfjs-2.6.347-dist/web/viewer.html?file=${fileSrc}&saveName=${fileName}`
            } else if (fileType === 'other') {
                this.fileSrc = `https://view.officeapps.live.com/op/embed.aspx?src=https://api-file.scdem.cn/api/Preview/v1/${fileId}`
            } else {
                this.fileSrc = fileSrc
            }
            let routeUrl = this.$router.resolve({
                path: '/preview',
                query: { fileSrc: this.fileSrc },
            })
            window.open(routeUrl.href, '_blank')
        },

        formatTable(arr, level = 1, result = []) {
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i]
                if (item.level === level) {
                    if (level === 1) {
                        item.selectable = false //一级节点禁止选择
                    }
                    item.scopedSlots = {
                        icon: 'custom',
                    }
                    item.status = Math.random() > 0.5 ? true : false
                    arr.splice(i, 1)
                    i--
                    result.push(item)
                    if (item.parentId) {
                        for (let j = 0; j < result.length; j++) {
                            let parent = result[j]
                            if (parent.templateId === item.parentId) {
                                if (!Array.isArray(parent.children)) {
                                    parent.children = []
                                }
                                parent.children.push(item)
                                break
                            }
                        }
                    }
                }
            }
            // 控制遍历的层级
            if (level > 1) {
                return
            }
            if (level > 4) {
                return console.error('模板数据异常')
            }
            if (arr.length > 0) {
                this.formatTable(arr, ++level, [...result])
            }
            return result
        },

        async getTemplate(id) {
            try {
                let res = await selfEvaluationApi.get({ id })
                let evaluationList = res?.data?.evaluationList || []
                this.originTreeData = evaluationList.sort((a, b) => a?.sortNum - b?.sortNum)
                // this.treeData = this.formatTable(this.originTreeData)
            } catch (e) {
                console.log(e)
            }
        },
        back() {
            this.$emit('typeChange', 'table')
        },
        save() {
            this.$emit('save')
        },
        async beforeUpload(file) {
            return await getFileToken({ file })
                .then(res => {
                    this.fileToken = res?.data?.token
                    return Promise.resolve()
                })
                .catch(() => {
                    return Promise.reject()
                })
        },
        tableChange(value, id, key) {
            console.log(value)
            for (let i = 0; i < this.originTreeData.length; i++) {
                let row = this.originTreeData[i]
                if (row.id === id) {
                    if (['zpScore', 'zhpScore', 'shScore'].includes(key)) {
                        if (typeof value !== 'number') {
                            return
                        }
                        if (value > row.score) {
                            this.$message.error('输入分值超过当前得分上限，将自动调整为' + row.score + '分')
                            value = row.score
                        }
                    }
                    row.ifRecord = true
                    row[key] = value
                    this.$set(this.originTreeData, i, row)
                    this.putChange(id)
                    break
                }
            }
        },
        treeSelected(selectedKeys, obj) {
            this.currentTreeNode = selectedKeys
            let node = null
            for (let i = 0; i < this.originTreeData.length; i++) {
                let item = this.originTreeData[i]
                if (item.templateId === selectedKeys[0]) {
                    node = item
                    break
                }
            }
            if (node?.encourage) {
                let arr = []
                for (let i = 0; i < this.columns.length; i++) {
                    let column = this.columns[i]
                    if (column.title.indexOf('缺项') === -1) {
                        arr.push(column)
                    }
                }
                this.columns = arr
            } else {
                this.columns = [...this._columns]
            }
        },
        handleTableChange() {
            this.getTableData()
        },
        getTableData() {
            return false
        },
        putChange: debounce(100, false, id => {
            // 通过id获取到最新的行数据
            let record = me.tableData.filter(item => item.id === id)[0] || {}
            if (me.$store.state.userInfo.roleCode > 2) {
                const { zhpMissItem, zhpScore, zhpRemarks, id } = record
                let params = {
                    templateRecordId: id,
                    zhpMissItem,
                    zhpScore,
                    zhpRemarks,
                }
                //静默保存
                selfEvaluationRecordApi.zh(params)
            } else {
                const { shMissItem, shScore, shRemarks, id } = record
                let params = {
                    templateRecordId: id,
                    shMissItem,
                    shScore,
                    shRemarks,
                }
                //静默保存
                selfEvaluationRecordApi.fh(params)
            }
        }),
    },
}
</script>

<style lang="scss" scoped>
.tab-box {
    height: calc(100vh - 370px);
    overflow-y: auto;
}
.file-content {
    height: 835px;
    &_header {
        border-bottom: 1px solid #d5d8de;
        padding: 32px 32px 0 32px;
        h1 {
            font-size: 24px;
            font-family: AlibabaPuHuiTiM, AlibabaPuHuiTiM-Regular;
            font-weight: 400;
            color: #243144;
            text-align: center;
        }
        .header-bot {
            font-size: 14px;
            font-family: AlibabaPuHuiTiR, AlibabaPuHuiTiR-Regular;
            font-weight: 400;
            color: rgba(36, 49, 68, 0.8);
            margin: 24px 0;
        }
    }
    &_content {
        padding: 32px;
        overflow-y: auto;
        height: calc(100% - 138px);
        /deep/ .ant-back-top {
            bottom: 380px;
        }
    }
}
</style>
